package console;

import java.util.Observable;
import java.util.Observer;

/**
 *
 * @author Michael Hanns
 *
 */
public class ClientObserver implements Observer {

    private ClientShell shell;
    private ClientGUI gui;
    private ClientPreferences prefs;
    private IOBuffer terminal;
    private InputHistory history;

    public ClientObserver(double softwareVersion, boolean osx) {
        if (osx) {
            gui = new console.gui.osx.ClientGUIImp(this, softwareVersion);
        } else {
            gui = new console.gui.windows.ClientGUIImp(this, softwareVersion);
        }
        prefs = new ClientPreferencesImp(true);
        terminal = new IOBufferImp();
        terminal.addObserver(this);
        history = new InputHistoryImp();
        shell = new ClientShellImp(terminal);
    }
    
    public ClientGUI getGUI() {
        return gui;
    }

    public void launchGUI() {
        gui.setVisible(true);
    }

    public void sendToShell(String input) {
        history.addLine(input.trim());
        if (prefs.isLocalEcho()) {
            terminal.writeTo("\n>" + input + "\n");
        }
        shell.inputLine(input);
    }

    public String getHistory(boolean previous) {
        if (previous) {
            return history.getLastLine();
        } else {
            return history.getNextLine();
        }
    }

    @Override
    public void update(Observable target, Object o) {
        String text = ((IOBuffer) target).getText();
        gui.updateGUITerminal(text);
    }
}
